import $U from '@/common/util.js';
import env from '@/env.js';
import envConfig from '@/env_config';
const $C = envConfig[env];

export default {
	common: {
		method: 'GET',
		header: {
			"content-type": "application/json"
		},
		data: {}
	},
	request(options = {}) {
		// 验证权限 -- 登录和注册接口不需要token
		if (!options.token) {
			if (!(options.url === '/login' && options.method === 'POST') && !(options.url === '/users' && options
					.method ===
					'POST')) {
				uni.showToast({
					title: '请重新登录',
					icon: 'error',
				});
				$U.redirectTo('login');
				return Promise.reject();
			}
		}

		options.url = $C.api_url + options.url;
		options.method = options.method || this.common.method;
		options.header = options.header || this.common.header;
		options.header.token = options.token;

		return new Promise((res, rej) => {
			uni.request({
				...options,
				success: (result) => {
					// 返回原始数据
					if (options.native) {
						return res(result)
					}
					// 请求服务端失败
					if (result.statusCode !== 200 && result.statusCode !== 201) {
						uni.showToast({
							title: result.data.msg || '请求失败',
							icon: 'none'
						});
						return rej(result.data)
					}
					// 成功
					res(result.data)
				},
				fail: (error) => {
					uni.showToast({
						title: error.errMsg || '请求失败',
						icon: 'none'
					});
					return rej()
				}
			});
		})
	},
	get(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
}
